<template>
    <el-table ref="multipleTableRef" :data="tableData" show-overflow-tooltip @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <template v-for="item in TaskManageCfg.items ">
            <el-table-column :type="item.type" :label="item.label" :width="item.width" v-if="item.type">
                <template v-slot="index_scope" v-if="item.scope">
                    <span>{{ (page - 1) * pageSize + index_scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column :fixed="item.fixed" :label="item.label" :width="item.width" v-else-if="item.fixed">
                <template v-slot="oprate" v-if="item.scope == 'oprate'">
                    <el-button link type="primary" size="small" @click="manageDelete(oprate.row)">删除</el-button>
                    <el-button link type="primary" size="small" @click="manageUpdate(oprate.row)">修改</el-button>
                </template>
            </el-table-column>
            <el-table-column v-else :prop='item.prop' :label="item.label" :width="item.width">
                <template v-slot="format_run_time" v-if="item.scope == 'format_run_time'">
                    <span>{{ formatDate(format_run_time.row.run_time) }}</span>
                </template>
                <template v-slot="format_start_time" v-if="item.scope == 'format_start_time'">
                    <span>{{ formatDate(format_start_time.row.start_time) }}</span>
                </template>
                <template v-slot="format_end_time" v-if="item.scope == 'format_end_time'">
                    <span>{{ formatDate(format_end_time.row.end_time) }}</span>
                </template>
                <template v-slot="task_status" v-if="item.scope == 'task_status'">
                    <span :style="getTaskStatusColor(task_status.row.task_status)">{{ task_status.row.task_status }}</span>
                </template>
            </el-table-column>
        </template>
    </el-table>
    <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[20, 50, 100, 200, 300, 400]"
        layout="total, sizes, prev, pager, next" :total="total" @prev-click='prevClick' @next-click='nextClick'
        @current-change='currentChange' @size-change="handleSizeChange" />
    <el-dialog v-model="dialogCfg.dialog_visible" :title="dialogCfg.title" width="500" align-center>
        <span v-if="dialogCfg.span">{{ dialogCfg.span }}</span>
        <template v-if="dialogCfg.form_select">
            <div v-for="item in dialogCfg.form_select">
                <span style="display: inline-block ;width: 70px;">{{ item.label }}</span>
                <el-select v-if="item.options" v-model="dialogCfg.form_model[item.model]"
                    :placeholder="`请选择${item.label}`" size="large" style="width: 240px">
                    <el-option v-for="i in item.options" :key="i.value" :label="i.label" :value="i.value" />
                </el-select>
            </div>
        </template>
        <template v-if="dialogCfg.form_item">
            <el-form :model="dialogCfg.form_item">
                <el-form-item :label="item.label" :label-width="70" v-for="item in dialogCfg.form_item">
                    <el-input width="100px" v-model="dialogCfg.form_model[item.model]" autocomplete="off" />
                </el-form-item>
            </el-form>
        </template>
        <template v-if="dialogCfg.date_picker">
            <div v-for="item in dialogCfg.date_picker">
                <span style="display: inline-block ;width: 70px;">{{ item.label }}</span>
                <el-date-picker v-model="dialogCfg.form_model[item.model]" type="datetime" placeholder="选择日期和时间" />
            </div>
        </template>
        <template #footer v-if="dialogCfg.footer">
            <div class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取消</el-button>
                <el-button v-if="dialogCfg.name === 'delete_task'" type="primary" @click="delete_task">
                    确定
                </el-button>
                <el-button v-if="dialogCfg.name === 'updata_task'" type="primary" @click="update_task">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'

import api from '@/api/index.js'
const tableData = ref([])
const page = ref(1)
const pageSize = ref(20)
const total = ref(20)
const currentRow = ref()
const dialogCfg = ref({})
const centerDialogVisible = ref(false)
const statu_color = reactive({
    WAITING:"blue",
    STATTED:"orange",
    SUCCESS:"green",
    FAIL:"red"
})
const getTaskStatusColor =(taskStatus)=> {
    return `color:${statu_color[taskStatus]};`;
  }
const TaskManageCfg = reactive({
    name: "TaskManageCfg",
    items: [
        { 'type': 'index', 'label': '序号', 'width': '60px', 'scope': true },
        { 'prop': 'task_type', 'label': '任务类型', 'width': '170px' },
        { 'prop': 'yingdao_uuid', 'label': '执行的影刀', 'width': '200px' },
        { 'prop': 'paramaters', 'label': '任务参数', 'width': null, },
        { 'prop': 'run_time', 'label': '定时时间', 'width': '170px', "scope": "format_run_time" },
        { 'prop': 'start_time', 'label': '任务开始时间', 'width': "170px", "scope": "format_start_time" },
        { 'prop': 'end_time', 'label': '任务结束时间', 'width': "170px", "scope": "format_end_time" },
        { 'prop': 'failure_reason', 'label': '失败原因', 'width': null},
        { 'prop': 'task_status', 'label': '任务状态', 'width': "120px", "scope": "task_status" },
        { 'fixed': 'right', 'label': '操作', 'width': "100px", "scope": "oprate" },
    ]
})

const dialogCfgs = reactive({
    delete_task: {
        name: "delete_task",
        dialog_visible: false,
        title: "警告",
        footer: true,
        span: "确定要删除这条任务吗？！"
    },
    updata_task: {
        name: "updata_task",
        dialog_visible: false,
        title: "修改任务",
        footer: true,
        form_select: [
            {
                label: "执行的影刀", model: "yingdao_uuid", options: [
                    { value: '747756521822392320', label: 'A_chaochuang' },
                    { value: '747756640630800384', label: 'B_chaochuang' },
                    { value: '747756787495956480', label: 'C_chaochuang' },
                    { value: '747700956819697664', label: '王经理' },
                ]
            },
            {
                label: "任务状态", model: "task_status", options: [
                    { value: 'WAITING', label: '未开始' },
                    { value: 'STATTED', label: '进行中' },
                    { value: 'SUCCESS', label: '执行成功' },
                    { value: 'FAIL', label: '任务失败' },
                ]
            },
        ],
        form_item: [
            { label: "任务参数", model: "paramaters" }
        ],
        // date_picker: [{ label: "定时时间", model: "run_time" }],
        form_model: {
            yingdao_uuid: null,
            paramaters: null,
            task_status: null,
            // run_time: null
        }
    }
})

const formatDate = (dateStr) => {
    if (dateStr) {
        const date = new Date(dateStr);
        return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
    } else {
        return null
    }
}

const get_tasks = (args = {}) => {
    const params = { pnum: page.value, psize: pageSize.value }
    api.get_tasks({ ...params, ...args }).then(res => {
        tableData.value = res.data.data.data
        total.value = res.data.data.total
    })
}

const manageUpdate = (row) => {
    currentRow.value = row;
    dialogCfg.value = dialogCfgs.updata_task
    dialogCfg.value.form_model = row
    dialogCfg.value.dialog_visible = true

}

const manageDelete = (row) => {
    currentRow.value = row;
    dialogCfg.value = dialogCfgs.delete_task
    dialogCfg.value.dialog_visible = true
}

const update_task = () => {
    api.update_task(currentRow.value.id, dialogCfg.value.form_model).then(res => {
        if (res.data.status === 200) {
            ElMessage({
                message: '修改成功.',
                type: 'success',
            })
            get_tasks()
        }
    })
    dialogCfg.value.dialog_visible = false
    dialogCfg.value.form_model = {
        yingdao_uuid: null,
        paramaters: null,
        task_status: null,
        // run_time: null
    }
}

const delete_task = () => {
    api.delete_task(currentRow.value.id).then(res => {
        if (res.data.status === 200) {
            ElMessage({
                message: '删除成功.',
                type: 'success',
            })
            get_tasks()
        }
    })
    dialogCfg.value.dialog_visible = false
}

onMounted(() => {
    get_tasks()
})
const prevClick = (e) => {
    get_tasks()
}

const nextClick = (e) => {
    get_tasks()
}

const currentChange = (e) => {
    page.value = e
    get_tasks()
}
const handleSizeChange = (val) => {
    pageSize.value = val
    get_tasks()
}
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}
</script>